from apps.goods.models import GoodsChannel


def get_categories():
    """获取商品分类（首页使用）"""
    from collections import OrderedDict

    categories = OrderedDict()

    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 一级分类
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        # 遍历二级分类
        for cat2 in cat1.subs.all().order_by('id'):
            sub_cat3_list = []
            for cat3 in cat2.subs.all().order_by('id'):
                sub_cat3_list.append({
                    'id': cat3.id,
                    'name': cat3.name
                })
            categories[group_id]['sub_cats'].append({
                'id': cat2.id,
                'name': cat2.name,
                'sub_cats': sub_cat3_list
            })

    return categories
